<template>
  <div v-loading.lock="loading" class="base-content">
    <div class="basic-info">
      <el-form ref="queryForm" :inline="true" :model="queryForm">
        <el-form-item :label="dataList.RecordNumber" prop="num">
          <el-input
            v-model="queryForm.num"
            :placeholder="dataList.RecordNumber"
          />
        </el-form-item>
        <el-form-item :label="dataList.DeviceNumber" prop="deviceNum">
          <el-input
            v-model="queryForm.deviceNum"
            :placeholder="dataList.DeviceNumber"
          />
        </el-form-item>
        <el-form-item
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
          prop="deviceName"
        >
          <el-input
            v-model="queryForm.deviceName"
            :placeholder="
              $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
            "
          />
        </el-form-item>
        <el-form-item :label="dataList.UsageName" prop="userName">
          <el-input
            v-model="queryForm.userName"
            :placeholder="dataList.UsageName"
          />
        </el-form-item>
        <el-form-item :label="dataList.Status" prop="state">
          <el-select
            v-model="queryForm.state"
            :placeholder="dataList.Placeholder"
          >
            <el-option
              v-for="item in stateList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="dataList.BeginUsageTime" prop="startTimeList">
          <el-date-picker
            v-model="queryForm.startTimeList"
            type="datetimerange"
            :range-separator="dataList.To"
            :start-placeholder="dataList.StartDate"
            :end-placeholder="dataList.EndDate"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div class="base-content-operate">
        <el-button type="primary" @click="onQuery">{{ btn.Query }}</el-button>
        <el-button @click="cancelForm">{{ btn.Reset }}</el-button>
        <el-button
          v-rights="'Add'"
          icon="el-icon-plus"
          type="primary"
          @click="onNew"
          >{{ btn.Add }}</el-button
        >
        <el-button v-rights="'Export'" type="primary" @click="exportLog">{{
          dataList.ExportRecord
        }}</el-button>
        <el-button v-rights="'Delete'" type="danger" @click="deleteData">{{
          btn.Delete
        }}</el-button>
      </div>

      <el-table
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
        height="calc(100% - 190px)"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          align="center"
          :label="dataList.Number"
          :width="$i18n.locale === 'en' ? 80 : 50"
        >
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.RecordNumber">
          <template slot-scope="scope">
            <el-link type="primary" @click="toView(scope.row)">
              {{ scope.row.num }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceNumber">
          <template slot-scope="scope">
            {{ scope.row.deviceNum }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
        >
          <template slot-scope="scope">
            {{ scope.row.deviceName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceSpecifications">
          <template slot-scope="scope">
            {{ scope.row.specifications }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.BeginUsageTime">
          <template slot-scope="scope">
            {{ formatTime(scope.row.startTime, "YYYY-MM-DD HH:mm") }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.EndUsageTime">
          <template slot-scope="scope">
            {{ formatTime(scope.row.endTime, "YYYY-MM-DD HH:mm") }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DurationOfUsage">
          <template slot-scope="scope">
            {{ scope.row.useTime }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.ReasonsOfUsage">
          <template slot-scope="scope">
            {{ scope.row.reasonsForUsing }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.PreUseStatus">
          <template slot-scope="scope">
            {{ scope.row.deviceFrontStateLabel }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.PostUseStatus">
          <template slot-scope="scope">
            {{ scope.row.deviceLaterStateLabel }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.UsageName">
          <template slot-scope="scope">
            {{ scope.row.userName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Rocorder">
          <template slot-scope="scope">
            {{ scope.row.creatorName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.RecordSource">
          <template slot-scope="scope">
            {{ scope.row.recordSourceLabel }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Status">
          <template slot-scope="scope">
            {{ scope.row.stateLabel }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Operation">
          <template slot-scope="scope">
            <div v-if="scope.row.state == 1" class="base-table-operation">
              <el-link
                v-rights="'Update'"
                size="mini"
                type="primary"
                @click="toEdit(scope.row)"
                >{{ btn.Edit }}</el-link
              >
            </div>
            <div v-if="scope.row.state == 0" class="base-table-operation">
              <el-link
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)"
                >{{ dataList.UsageEnd }}</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <BasePagination
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
    </div>

    <el-dialog
      v-if="useFinishVisible"
      class="base-dialog system-user-dialog"
      :append-to-body="true"
      :title="dataList.UsageEnd"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="useFinishVisible"
    >
      <div>
        <el-form
          ref="formData"
          :label-width="formLabelWidth"
          :model="formData"
          :rules="formDataRules"
          status-icon
        >
          <el-form-item
            :label="dataList.EndUsageTime"
            :label-width="formLabelWidth"
            prop="endTime"
            :error="errorMsg.endTime"
          >
            <el-date-picker
              v-model="formData.endTime"
              style="width: 50%; float: left"
              type="datetime"
              :placeholder="dataList.SelectDateTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="returnDateOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            :label="dataList.PostUseStatus"
            :label-width="formLabelWidth"
            prop="deviceLaterState"
            :error="errorMsg.deviceLaterState"
          >
            <DicDropDownList
              v-model="formData.deviceLaterState"
              style="width: 50%; float: left"
              dict-code="deviceStatusList"
              :is-all="false"
              :display-text.sync="displayText"
            />
          </el-form-item>
          <el-form-item
            :label="dataList.Deviceremark"
            :label-width="formLabelWidth"
            prop="remake"
            :error="errorMsg.remake"
          >
            <el-input
              v-model="formData.remake"
              type="textarea"
              style="width: 50%; float: left"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          btn.Confirm
        }}</el-button>
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>

    <DeviceUsageLogAdd
      v-if="dialogFormVisible"
      :id.sync="id"
      ref="DeviceUsageLogEdit"
      :dialog-form-visible.sync="dialogFormVisible"
      @close="getList"
    />
    <DeviceUsageLogView
      v-if="viewVisible"
      :id.sync="id"
      ref="DeviceUsageLogView"
      :dialog-form-visible.sync="viewVisible"
    />
    <DeviceUsageLogEdit
      v-if="viewVisibleEdit"
      :id.sync="id"
      ref="DeviceUsageLogView"
      :dialog-form-visible.sync="viewVisibleEdit"
      @close="getList"
    />
  </div>
</template>

<script>
import {
  deleteRecord,
  getList,
  DeviceUsageFinish,
} from "../../api/DeviceUsageLog.js";
import DeviceUsageLogAdd from "./DeviceUsageLogAdd.vue";
import DeviceUsageLogView from "./DeviceUsageLogView.vue";
import DeviceUsageLogEdit from "./DeviceUsageLogEdit.vue";
import DicDropDownList from "../../components/DicDropDownList.vue";
import { normal } from "../../utils/const";
import { formatTime } from "../../utils/time";
import { DeviceExportExcel } from "../../api/Device.js";
export default {
  name: "DeviceUsageLogList",
  components: {
    DeviceUsageLogAdd,
    DicDropDownList,
    DeviceUsageLogView,
    DeviceUsageLogEdit,
  },
  data() {
    return {
      formatTime,
      formatJson(filterVal, jsonData) {
        return jsonData.map((v) =>
          filterVal.map((j) => {
            return v[j];
          })
        );
      },
      loading: true,
      startTime: null,
      formLabelWidth: "300px",
      id: "",
      list: [],
      tableDatas: [],
      stateList: [
        {
          label: this.$t("ModuleDevice.Device.All"),
          value: -1,
        },
        {
          label: this.$t("ModuleDevice.Device.Usaging"),
          value: 0,
        },
        {
          label: this.$t("ModuleDevice.Device.Completed"),
          value: 1,
        },
      ],
      displayText: [
        this.$t("ModuleDevice.Device.Normal"),
        this.$t("ModuleDevice.Device.Fault"),
        this.$t("ModuleDevice.Device.Downgrading"),
      ],
      formData: {
        id: "",
        endTime: null,
        deviceLaterState: normal,
        remake: "",
      },
      tHeader: [
        this.$t("ModuleDevice.Device.RecordNumber"), // "记录编号",
        this.$t("ModuleDevice.Device.DeviceNumber"), // "设备编号",
        this.$t("ModuleDevice.Device.DeviceName"), // "设备名称",
        this.$t("ModuleDevice.Device.BeginUsageTime"), // "开始使用时间",
        this.$t("ModuleDevice.Device.EndUsageTime"), // "结束使用时间",
        this.$t("ModuleDevice.Device.DurationOfUsage"), //  "使用时长",
        this.$t("ModuleDevice.Device.ReasonsOfUsage"), // "使用设备原因",
        this.$t("ModuleDevice.Device.PreUseStatus"), // "使用前状态",
        this.$t("ModuleDevice.Device.PostUseStatus"), // "使用后状态",
        this.$t("ModuleDevice.Device.UsageName"), // "设备使用人",
        this.$t("ModuleDevice.Device.Rocorder"), //  "记录人",
        this.$t("ModuleDevice.Device.Deviceremark"), //  "备注",
      ],
      filterVal: [
        "num",
        "deviceNum",
        "deviceName",
        "startTime",
        "endTime",
        "useTime",
        "reasonsForUsing",
        "deviceFrontStateLabel",
        "deviceLaterStateLabel",
        "userName",
        "creatorName",
        "remake",
      ],
      formDataRules: {
        endTime: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        deviceLaterState: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      returnDateOptions: {
        // 限制日期
        disabledDate: (time) => {
          return time.getTime() < new Date(this.startTime).getTime();
        },
      },
      queryForm: {
        num: "",
        deviceNum: "",
        deviceName: "",
        userName: "",
        state: -1,
        startTimeList: [],
        createTimeStart: null,
        createTimeEnd: null,
        departId: sessionStorage.getItem("currentDepartmentId"),
      },
      viewVisible: false,
      viewVisibleEdit: false,
      useFinishVisible: false,
      dialogFormVisible: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      errorMsg: {
        endTime: "",
        deviceLaterState: "",
        remake: "",
      },
    };
  },
  computed: {
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  created() {
    this.getList();
  },
  methods: {
    handleSelectionChange(val) {
      this.tableDatas = val;
    },
    base64ToBlob(base64String, contentType) {
      contentType = contentType || "";
      var sliceSize = 1024;
      var byteCharacters = atob(base64String);
      var bytesLength = byteCharacters.length;
      var slicesCount = Math.ceil(bytesLength / sliceSize);
      var byteArrays = new Array(slicesCount);

      for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);
        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
          bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
      }
      return new Blob(byteArrays, { type: contentType });
    },
    // 导出
    exportLog() {
      this.queryForm.departId = sessionStorage.getItem("currentDepartmentId");
      DeviceExportExcel({
        type: 4,
        deviceUsageLogGetListRequest: this.queryForm,
      }).then((res) => {
        if (res.data != null) {
          var base64String = res.data;
          var blob = this.base64ToBlob(
            base64String,
            "application/vnd.ms-excel"
          );
          // 创建一个可下载的链接
          var url = URL.createObjectURL(blob);
          var link = document.createElement("a");
          link.href = url;
          link.setAttribute(
            "download",
            this.$t("ModuleDevice.Device.DeviceUsageLogList") + ".xlsx"
          ); // 设置文件名

          // 模拟点击链接进行下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          this.$message.error(this.$t("ModuleDevice.Message.NoData"));
        }
      });
    },
    // 删除
    deleteData() {
      for (let i = 0; i < this.tableDatas.length; i++) {
        if (Number(this.tableDatas[i].state) === 1) {
          this.$message.error(
            this.$t("ModuleDevice.Message.DeleteUsageRecordFail")
          ); // "不能删除已完成数据请重新选择");
          return false;
        }
      }

      this.Helper.deleteConfirm(() => {
        this.loading = true;
        deleteRecord({ idList: this.tableDatas.map((x) => x.id) })
          .then((res) => {
            this.getList();
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.formData.endTime < this.startTime) {
            this.$message.error(
              this.$t("ModuleDevice.Message.BeginTimeLessEndTime")
            );
            return false;
          }

          DeviceUsageFinish(this.formData).then((res) => {
            this.cancel();
            this.getList();
          });
        } else {
          return false;
        }
      });
    },
    toView(row) {
      this.id = row.id;
      this.viewVisible = true;
    },
    toEdit(row) {
      this.id = row.id;
      this.viewVisibleEdit = true;
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    cancelForm() {
      this.queryForm.createTimeStart = null;
      this.queryForm.createTimeEnd = null;
      this.$refs.queryForm.resetFields();
      this.pagination.pageIndex = 1;
      this.getList();
    },
    getList() {
      this.loading = true;

      getList(this.queryForm, this.pagination)
        .then((res) => {
          this.list = res.data.dataList ? res.data.dataList : [];
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onNew() {
      this.dialogFormVisible = true;
    },
    cancel() {
      this.useFinishVisible = false;
    },
    handleEdit(rowData) {
      this.formData.id = rowData.id;
      this.startTime = rowData.startTime;
      this.formData.endTime = formatTime(new Date(), "YYYY-MM-DD HH:mm:ss");
      this.useFinishVisible = true;
    },
    onQuery() {
      this.pagination.pageIndex = 1;
      if (
        this.queryForm.startTimeList !== null &&
        this.queryForm.startTimeList.length !== 0
      ) {
        this.queryForm.createTimeStart =
          this.queryForm.startTimeList[0] + " 00:00:00";
        this.queryForm.createTimeEnd =
          this.queryForm.startTimeList[1] + " 23:59:59";
      }
      this.getList();
    },
  },
};
</script>
